//
//  MKBookshelfViewController.m
//  ManKeCartoon
//
//  Created by 邹功梁 on 15/10/16.
//  Copyright © 2015年 ManKe. All rights reserved.
//

#import "MKBookshelfViewController.h"
#import "MKDownloadBrowseViewController.h"
#import "MKBaseHeader.h"
#import "CoreDataManager.h"
#import "DownloadData.h"
#import "SDWebImageManager.h"
#import "URLCache.h"
#import "DownManager.h"
@interface MKBookshelfViewController ()<UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, retain) CoreDataManager *coreDataManager;

@property (nonatomic, retain) NSMutableArray *current_imgArray; // 存放需要下载的图片url
@property (nonatomic, retain) NSMutableArray *searchResultArray; // 查找后存放数据的数组
@property (nonatomic, retain) NSMutableDictionary *downloadDic; // 查找后的存放对应Model的字典

@property (nonatomic, retain) NSMutableDictionary *hasDownloadDic; // 存放已经下好的装有图片的数组
@property (nonatomic, retain) NSMutableDictionary *comicHasDownloadDic;
@property (nonatomic, retain) NSMutableArray *hasDownloadImageArray; // 存放已经下载好的图片

@property (nonatomic, retain) NSMutableArray *needDownloadArray; // 需要下载的对应Model数组

@property (nonatomic, retain) NSMutableArray *comic_idArray; // comic_id数组

@property (nonatomic, assign) NSInteger tempCount; // 计数下载集数
@property (nonatomic, assign) NSInteger seq_noCount;
@property (nonatomic, assign) NSInteger progressCount;
@property (nonatomic, copy) NSString *comic_id;

@property (nonatomic, copy) NSString *seq_no;
@end

@implementation MKBookshelfViewController

- (void)viewWillAppear:(BOOL)animated{
    if (_downloadTableView != nil) {
        [_downloadTableView reloadData];
    }
    _saveArray = [[DataBase shareDataBase] selectAll];
    [_saveCollectionView reloadData];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        _saveArray = [[NSMutableArray alloc] init];
        _chapterModelArray = [[NSMutableArray alloc] init];
        _searchResultArray = [[NSMutableArray alloc] init];
        _current_imgArray = [[NSMutableArray alloc] init];
        _downloadDic = [[NSMutableDictionary alloc] init];
        _needDownloadArray = [[NSMutableArray alloc] init];
        _hasDownloadImageArray = [[NSMutableArray alloc] init];
        _hasDownloadDic = [[NSMutableDictionary alloc] init];
        _comic_idArray = [[NSMutableArray alloc] init];
        _comicHasDownloadDic = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.coreDataManager = [CoreDataManager shareHandle];
    
    _tempCount = 0;
    _seq_noCount = 0;
    _progressCount = 0;
    // 调用查找
    [self searchDownloadData];
    [self getData];
    
    [self createSaveButton];
    [self createDownloadButton];
    [self createDeleteButton];
    
    [self createScrollView];
    [self createCollectionView];
    [self createTableView];
}
#pragma mark - 数据获取
- (void)getData
{
    NSArray *array = [_downloadDic.allKeys sortedArrayUsingSelector:@selector(compare:)];
    // 判断控制_tempCount<数组元素个数
    if (_tempCount < array.count) {
        // 取出key即comic_id
        _comic_id = array[_tempCount];
        // 把comic_id加入到存放comic_id数组中
        [_comic_idArray addObject:_comic_id];
        // 取出第一个漫画
        _needDownloadArray = [_downloadDic objectForKey:_comic_id];
        
        // 递归第一层 如果第一个漫画---- 下载好的集数==取出的对应需要下载的集数则跳出递归
        if (_needDownloadArray.count != _seq_noCount) {
            // 取出第一个漫画对应的第一集🐔
            MKChaptersModel *model = [_needDownloadArray objectAtIndex:_seq_noCount];
            // 当前正在下载的集数
            _seq_no = model.seq_no;
            [AFNETWORK getDataWithNoCacheString:[NSString stringWithFormat:@"http://mobilev3.ac.qq.com/Comic/chapterPictureListV2/chapter_id/%@/comic_id/%@", model.chapter_id, array[_tempCount]] block:^(id block) {
                _current_imgArray = [[NSMutableArray alloc] init];
                for (NSDictionary *dic in [[block objectForKey:@"data"] objectForKey:@"img_infos"]) {
                    MKImageInfosModel *imageInfoModel = [[MKImageInfosModel alloc] initWithDictionary:dic];
                    // 将该集所有的图片请求后存到数组中
                    [_current_imgArray addObject:imageInfoModel.current_img_url];
                }
                // 对当前存放下载好的图片数组重初始化
                _hasDownloadImageArray = [[NSMutableArray alloc] init];
                // 调用下载图片方法
                [self downloadComicImage];
            }];
        }
        else
        {
//            NSLog(@"%@", _comicHasDownloadDic);
            
            _hasDownloadDic = [[NSMutableDictionary alloc] init];
            _tempCount++;
            _seq_noCount = 0;

            [self getData];
        }
    }
    else
    {
        [[SDImageCache sharedImageCache] cleanDisk];
    }
}
#pragma mark - 图片下载
- (void)downloadComicImage
{
    _progressCount = 0;
    for (NSString *imageUrl in _current_imgArray) {
        SDWebImageManager *imageManager = [SDWebImageManager sharedManager];
        [imageManager downloadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageContinueInBackground progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
            
            if (finished) {
                _progressCount++;
                NSString *path = [DownManager createSubDocumentFile:_comic_id subFile:_seq_no];
                NSString *filePath = [path stringByAppendingString:[NSString stringWithFormat:@"/%@_%@_%ld.png", _comic_id, _seq_no, _progressCount]];
                [UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES];

                [_hasDownloadImageArray addObject:image];
            }
            // 如果下载好的图片数组元素个数 == 该集图片个数
            if (_hasDownloadImageArray.count == _current_imgArray.count) {
                // 将下载好的存放到对应的key(seq_no)
                [_hasDownloadDic setValue:_hasDownloadImageArray forKey: _seq_no];
                // 将存放下载数据的字典存到对应key(comic_id) 的大字典中
                [_comicHasDownloadDic setValue:_hasDownloadDic forKey:_comic_id];
                // 作为计数
                _seq_noCount++;
                [_downloadTableView reloadData];
                // 下完该集重新调用 继续下载下一集
                [self getData];
            }
            
        }];
    }
}
#pragma mark - 查找下载数组
- (void)searchDownloadData
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"DownloadData" inManagedObjectContext:self.coreDataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"comic_id"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"[Error] %@", error);
    }
    
    self.searchResultArray = [fetchedObjects mutableCopy];
    
    for (DownloadData *down in fetchedObjects) {
        
//        // Data 转 Array
        _chapterModelArray = [NSKeyedUnarchiver unarchiveObjectWithData:down.downloadData];
        
        [_downloadDic setValue:_chapterModelArray forKey:down.comic_id];
    }
}
#pragma mark - 创建收藏按钮
- (void)createSaveButton {
    
    _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _saveButton.frame = CGRectMake(10, 24, 60, 30);
    [self.navBarView addSubview:_saveButton];
    [_saveButton setBackgroundColor:[UIColor greenColor]];
    
    [_saveButton setTitle:@"收藏" forState:UIControlStateNormal];
    
    [_saveButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_saveButton setBackgroundColor:[UIColor whiteColor]];
    _saveButton.layer.cornerRadius = 15;
    _saveButton.layer.borderWidth = 1;
    _saveButton.layer.borderColor = [UIColor colorWithRed:0.91 green:0.42 blue:0.24 alpha:1].CGColor;
    [_saveButton addTarget:self action:@selector(saveClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma marka - 下载按钮
- (void)createDownloadButton
{
    _downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _downloadButton.frame = CGRectMake(90, 24, 60, 30);
    [self.navBarView addSubview:_downloadButton];
    [_downloadButton setBackgroundColor:[UIColor greenColor]];
    
    [_downloadButton setTitle:@"下载" forState:UIControlStateNormal];
    
    [_downloadButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_downloadButton setBackgroundColor:[UIColor whiteColor]];
    _downloadButton.layer.cornerRadius = 15;
    _downloadButton.layer.borderWidth = 1;
    _downloadButton.layer.borderColor = [UIColor colorWithRed:0.91 green:0.42 blue:0.24 alpha:1].CGColor;
    [_downloadButton addTarget:self action:@selector(downloadClick:) forControlEvents:UIControlEventTouchUpInside];
}
#pragma mark - 保存按钮点击方法
- (void)saveClick:(UIButton *)sender
{
    [_downloadButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_downloadButton setBackgroundColor:[UIColor whiteColor]];
    [_saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_saveButton setBackgroundColor:[UIColor colorWithRed:0.91 green:0.42 blue:0.24 alpha:1]];
    _saveButton.layer.borderColor = [UIColor whiteColor].CGColor;
    [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
    _deleteButton.hidden = NO;
}
#pragma mark - 下载按钮点击方法
- (void)downloadClick:(UIButton *)sender
{
    [_saveButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [_saveButton setBackgroundColor:[UIColor whiteColor]];
    [_downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_downloadButton setBackgroundColor:[UIColor colorWithRed:0.91 green:0.42 blue:0.24 alpha:1]];
    _downloadButton.layer.borderColor = [UIColor whiteColor].CGColor;
    [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:NO];
    _deleteButton.hidden = YES;
}
#pragma mark - 创建删除按钮
- (void)createDeleteButton {
    
    _deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _deleteButton.frame = CGRectMake(SCREEN_WIDTH-40, 24, 30, 30);
    [_deleteButton setImage:[UIImage imageNamed:@"iconfont-delete.png"] forState:UIControlStateNormal];
    [self.navBarView addSubview:_deleteButton];
    [_deleteButton addTarget:self action:@selector(deleteClick:) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark - 删除按钮点击方法
- (void)deleteClick:(UIButton *)sender {
    
    if (self.tabBarController.tabBar.hidden == NO) {
        self.tabBarController.tabBar.hidden = YES;
        sender.selected = YES;
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.frame = CGRectMake(0, SCREEN_HEIGHT-49, SCREEN_WIDTH, 49);
        [_cancelButton setBackgroundColor:[UIColor whiteColor]];
        [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [self.view addSubview:_cancelButton];
        [_cancelButton addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
        UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _cancelButton.frame.size.width, 1)];
        [grayView setBackgroundColor:[UIColor colorWithRed:230/255. green:230 /255. blue:230/255. alpha:1.]];
        [_cancelButton addSubview:grayView];
    }
    
}
#pragma mark - 取消按钮
- (void)cancelClick{
    
    [_cancelButton removeFromSuperview];
    self.tabBarController.tabBar.hidden = NO;
    _deleteButton.selected = NO;
}
#pragma mark - 创建scrollView
- (void)createScrollView {
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-49-64)];
    [_scrollView setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:_scrollView];
    
    [_scrollView setContentSize:CGSizeMake(SCREEN_WIDTH*2, 0)];
    [_scrollView setPagingEnabled:YES];
    [_scrollView setBounces:NO];
    _scrollView.scrollEnabled = NO;
    _scrollView.showsHorizontalScrollIndicator = NO;
    if (_comicModel != nil) {
        [_saveButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_saveButton setBackgroundColor:[UIColor whiteColor]];
        [_downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_downloadButton setBackgroundColor:[UIColor colorWithRed:0.91 green:0.42 blue:0.24 alpha:1]];
        _downloadButton.layer.borderColor = [UIColor whiteColor].CGColor;
        [_scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0) animated:NO];
        _deleteButton.hidden = YES;
    }
    else
    {
        [_downloadButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_downloadButton setBackgroundColor:[UIColor whiteColor]];
        [_saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_saveButton setBackgroundColor:[UIColor colorWithRed:0.91 green:0.42 blue:0.24 alpha:1]];
        _saveButton.layer.borderColor = [UIColor whiteColor].CGColor;
        [_scrollView setContentOffset:CGPointMake(0, 0) animated:NO];
        _deleteButton.hidden = NO;
    }
    
    [_scrollView setDelegate:self];

}
#pragma mark - 创建collectionView
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-40)/3, (SCREEN_HEIGHT-20-44-49)/3);
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    _saveCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-48) collectionViewLayout:flowLayout];
    
    [_scrollView addSubview:_saveCollectionView];
    
    [_saveCollectionView setBackgroundColor:[UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1]];
    _saveCollectionView.delegate = self;
    _saveCollectionView.dataSource = self;
    
    [_saveCollectionView registerClass:[MKSaveCollectionViewCell class] forCellWithReuseIdentifier:@"saveCollectionViewCell"];
}
#pragma mark - 创建tableview 
- (void)createTableView
{
    _downloadTableView = [[UITableView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStylePlain];
    _downloadTableView.delegate = self;
    _downloadTableView.dataSource = self;
    _downloadTableView.estimatedRowHeight = 130 * HEIGHT;
    _downloadTableView.backgroundColor = [UIColor colorWithRed:0.98 green:0.98 blue:0.98 alpha:1];
    _downloadTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_scrollView addSubview:_downloadTableView];
}
#pragma mark - TableView DataSource & Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140 * HEIGHT;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _searchResultArray.count;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"reuseIdentifier";
    MKDownloadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[MKDownloadTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    DownloadData *data = [_searchResultArray objectAtIndex:indexPath.row];
    _chapterModelArray = [_downloadDic objectForKey:data.comic_id];
    NSDictionary *dic = [_comicHasDownloadDic objectForKey:data.comic_id];
    if ([data.comic_id isEqualToString:_comic_id]) {
        cell.progressView.progress = (CGFloat)dic.allKeys.count / _chapterModelArray.count;
        [cell setDownloadData:data now:dic.allKeys.count all:_chapterModelArray.count];
    }
    else
    {
        cell.progressView.progress = (CGFloat)dic.allKeys.count / _chapterModelArray.count;
        [cell setDownloadData:data now:dic.allKeys.count all:_chapterModelArray.count];
    }
    return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        DownloadData *downloadData = [_searchResultArray objectAtIndex:indexPath.row];
        
        [self.coreDataManager.managedObjectContext deleteObject:downloadData];
        
        [_searchResultArray removeObjectAtIndex:indexPath.row];
        [DownManager deleteDocumentFile:downloadData.comic_id];
        
        [self.coreDataManager saveContext];
        
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DownloadData *data = [_searchResultArray objectAtIndex:indexPath.row];
    NSMutableDictionary *dic = [_comicHasDownloadDic objectForKey:data.comic_id];
    MKDownloadBrowseViewController *browse = [[MKDownloadBrowseViewController alloc] init];
    browse.downData = data;
    browse.comicDic = dic;
    [self.navigationController pushViewController:browse animated:YES];
}
#pragma mark - CollectionView DataSource & Delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _saveArray.count;
    
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    MKSaveCollectionViewCell *collectionViewCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"saveCollectionViewCell" forIndexPath:indexPath];
    if (collectionViewCell == nil) {
        collectionViewCell = [[MKSaveCollectionViewCell alloc] init];
    }

    [collectionViewCell getDataWithModel:[_saveArray objectAtIndex:indexPath.row]];
    collectionViewCell.backgroundColor = [UIColor whiteColor];
    return collectionViewCell;
}
#pragma mark - collectionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MKCartoonViewController *cartoonViewController = [[MKCartoonViewController alloc] init];
    cartoonViewController.comic_id = [[_saveArray objectAtIndex:indexPath.row] comic_id];
    
    if (_deleteButton.selected) {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"确认删除选中的漫画?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAlertAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *comfirmAlertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [[DataBase shareDataBase] deleteBook:[_saveArray[indexPath.row] title]];
            [_saveArray removeObjectAtIndex:indexPath.row];
            [_saveCollectionView deleteItemsAtIndexPaths:@[indexPath]];
            
        }];
        [alertController addAction:cancelAlertAction];
        [alertController addAction:comfirmAlertAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    } else {
        
        [self.navigationController pushViewController:cartoonViewController animated:YES];
        
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
